local extension = Package:new("ze_heg_ex")
extension.extensionName = "ze_heg"
local H = require "packages/hegemony/util"
local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["ze_heg_ex"] = "将御千军",
  ["du_heg"] = "度",
}

-- 立状
--- 对某角色立状（抽取、选择、询问）
---@param from ServerPlayer @ 军令发起者
---@param to ServerPlayer @ 军令执行者
---@param skill_name string @ 技能名
---@param forced? boolean @ 是否强制执行
---@return boolean @ 是否执行
H.lizhuang = function(from, to, skill_name)
  if from.dead or to.dead then return false end
  local room = from.room
  room:sendLog{
    type = "#lizhuang",
    from = from.id,
    to = {to.id},
    arg = skill_name,
    toast = true,
  }
  --[[ -- 酷炫顶栏
  local ret = "<b><font color='#0C8F0C'>" .. Fk:translate(from.general)
  if from.deputyGeneral and from.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(from.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. Fk:translate("to") .. " <b><font color='#CC3131'>" .. Fk:translate(to.general)
  if to.deputyGeneral and to.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(to.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. " <b>" .. Fk:translate("start_command") .. "</b>"
  room:doBroadcastNotify("ServerMessage", ret)
  --]]
  local index = H.startLizhuang(from, skill_name)
  local invoke = H.doLizhuang(to, skill_name, index, from, forced)
  return invoke
end

--- 军令发起者抽取并选择军令
---@param from ServerPlayer @ 军令发起者
---@param skill_name string @ 技能名
---@return integer @ 选择的军令序号
H.startLizhuang = function(from, skill_name)
  local allcommands = {"command1", "command2", "command3", "command4", "command5", "command6"}
  local commands = table.random(allcommands, 1) ---@type string[]
  local room = from.room
  local choice = room:askForChoice(from, commands, "start_command", nil, true)
  room:sendLog{
    type = "#CommandChoice",
    from = from.id,
    arg = ":"+choice,
    toast = true,
  }
  --[[ -- 酷炫顶栏
  local ret = "<b><font color='#0C8F0C'>" .. Fk:translate(from.general)
  if from.deputyGeneral and from.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(from.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. Fk:translate("chose") .. " <b>" .. Fk:translate(":"+choice) .. "</b>"
  room:doBroadcastNotify("ServerMessage", ret)
  --]]

  return table.indexOf(allcommands, choice)
end

--- 询问军令执行者是否执行军令（执行效果也在这里）
---@param to ServerPlayer @ 军令执行者
---@param skill_name string @ 技能名
---@param index integer @ 军令序数
---@param from ServerPlayer @ 军令发起者
---@param forced? boolean @ 是否强制执行
---@return boolean @ 是否执行
H.doLizhuang = function(to, skill_name, index, from, forced)
  if to.dead or from.dead then return false end
  local room = to.room
  local allcommands = {"command1", "command2", "command3", "command4", "command5", "command6"}
  local choice
  if 1 == 1 then
    choice = room:askForChoice(to, {allcommands[index]}, "do_command", nil, true, {allcommands[index], "Cancel"})
  end
  local result = choice == "Cancel" and "#commandselect_no" or "#commandselect_yes"
  room:sendLog{
    type = "#CommandChoice",
    from = to.id,
    arg = result,
    toast = true,
  }
  --[[ -- 酷炫顶栏
  local ret = "<b><font color='#CC3131'>" .. Fk:translate(to.general)
  if to.deputyGeneral and to.deputyGeneral ~= "" then
    ret = ret .. "/" .. Fk:translate(to.deputyGeneral)
  end
  ret = ret .. "</b></font> " .. Fk:translate("chose") .. " <b>" .. Fk:translate(result) .. "</b>"
  room:doBroadcastNotify("ServerMessage", ret)
  --]]
  if choice == "Cancel" then return false end
  local commandData = {
    from = from,
    to = to,
    command = index,
  }
  if room.logic:trigger("fk.ChoosedoLizhuang", to, commandData) then
    room.logic:trigger("fk.AfterCommandUse", to, commandData)
    return true
  end
  if index == 1 then
    local dest = room:askForChoosePlayers(from, table.map(room.alive_players, Util.IdMapper), 1, 1, "#command1-damage::" .. to.id, skill_name)[1]
    room:sendLog{
      type = "#Command1Damage",
      from = from.id,
      to = {dest},
    }
    room:doIndicate(from.id, {dest})
    room:damage{
      from = to,
      to = room:getPlayerById(dest),
      damage = 1,
      skillName = "command",
    }
  elseif index == 2 then
    to:drawCards(1, "command")
    if to == from or to:isNude() then return true end
    local cards = {}
    if #to:getCardIds{Player.Hand, Player.Equip} == 1 then
      cards = to:getCardIds{Player.Hand, Player.Equip}
    else
      cards = room:askForCard(to, 2, 2, true, "command", false, nil, "#command2-give::" .. from.id)
    end
    room:moveCardTo(cards, Player.Hand, from, fk.ReasonGive, "command", nil, false, from.id)
  elseif index == 3 then
    room:loseHp(to, 1, "command")
  elseif index == 4 then
    room:setPlayerMark(to, "@@command4_effect-turn", 1)
    room:addPlayerMark(to, MarkEnum.UncompulsoryInvalidity .. "-turn")
    room:handleAddLoseSkills(to, "#command4_prohibit", nil, false, true) --为了不全局，流汗了
  elseif index == 5 then
    to:turnOver()
    room:setPlayerMark(to, "@@command5_effect-turn", 1)
    room:handleAddLoseSkills(to, "#command5_cannotrecover", nil, false, true) --为了不全局，流汗了
  elseif index == 6 then
    if to:getHandcardNum() < 2 and #to:getCardIds(Player.Equip) < 2 then return true end
    local to_remain = {}
    if not to:isKongcheng() then
      table.insert(to_remain, to:getCardIds(Player.Hand)[1])
    end
    if #to:getCardIds(Player.Equip) > 0 then
      table.insert(to_remain, to:getCardIds(Player.Equip)[1])
    end
    local _, ret = room:askForUseActiveSkill(to, "#command6_select", "#command6-select", false)
    if ret then
      to_remain = ret.cards
    end
    local cards = table.filter(to:getCardIds{Player.Hand, Player.Equip}, function (id)
      return not (table.contains(to_remain, id) or to:prohibitDiscard(Fk:getCardById(id)))
    end)
    if #cards > 0 then
      room:throwCard(cards, "command", to)
    end
  end
  room.logic:trigger("fk.AfterCommandUse", to, commandData)
  return true
end

Fk:loadTranslationTable{
  ["command"] = "军令",
  ["#startLizhuang"] = "%arg：请选择一项军令<br>%arg2；<br>%arg3",
  ["command1"] = "军令一",
  ["command2"] = "军令二",
  ["command3"] = "军令三",
  ["command4"] = "军令四",
  ["command5"] = "军令五",
  ["command6"] = "军令六",
  [":command1"] = "军令一：对发起者指定的角色造成1点伤害",
  [":command2"] = "军令二：摸一张牌，然后交给发起者两张牌",
  [":command3"] = "军令三：失去1点体力",
  [":command4"] = "军令四：本回合不能使用或打出手牌且所有非锁定技失效",
  [":command5"] = "军令五：叠置，本回合不能回复体力",
  [":command6"] = "军令六：选择一张手牌和一张装备区里的牌，弃置其余的牌",
  ["start_command"] = "发起军令",
  ["#lizhuang"] = "%from 发动了 “%arg”，对 %to 发起了 <font color='#0598BC'><b>军令",
  ["#CommandChoice"] = "%from 选择了 %arg",
  ["chose"] = "选择了",
  ["do_command"] = "执行军令",
  ["#commandselect_yes"] = "执行军令",
  ["#commandselect_no"] = "不执行军令",
  ["#command1-damage"] = "军令：请选择 %dest 伤害的目标",
  ["#Command1Damage"] = "%from 选择对 %to 造成伤害",
  ["#command2-give"] = "军令：请选择两张牌交给 %dest",
  ["@@command4_effect-turn"] = "军令禁出牌技能",
  ["@@command5_effect-turn"] = "军令 不能回血",
  ["#command6-select"] = "军令：请选择要保留的一张手牌和一张装备",
}

local caorui = General(extension, "du_heg__caorui", "wei", 3, 3, General.Male)
local cuzhan = fk.CreateTriggerSkill{
  name = "hurryfight",
  events = {fk.EventPhaseStart},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and target ~= player and target.phase == Player.Play and #player:getCardIds("he") > 1) then return false end
    return true
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForCard(player, 1, 1, true, self.name, true, ".", "#hurryfight-give")
    if #cards == 1 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:obtainCard(target, self.cost_data, false, fk.ReasonGive)
    if not target.dead then
      room:setPlayerMark(target, "@@hurryfight-turn", 1)
      room:setPlayerMark(target, "@@fight-turn", 1)
    end
  end
}
local fight_targetmod = fk.CreateTargetModSkill{
  name = "#fight_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@@fight-turn") > 0 and scope == Player.HistoryPhase then
      return player:getMark("@@fight-turn")
    end
  end,
}
local cuzhan_delay = fk.CreateTriggerSkill{
  name = "#hurryfight_delay",
  events = {fk.EventPhaseEnd},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not (target:getMark("@@hurryfight-turn") > 0 and target.phase == Player.Play and player:usedSkillTimes(cuzhan.name, Player.HistoryTurn) > 0 and player:isAlive()) then return false end
    return #player.room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == target
    end, Player.HistoryPhase) == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if H.lizhuang(player, target, self.name) then
    else
      return false
    end
  end,
}
local tingsong = fk.CreateTriggerSkill{
  name = "hearlawsuit",
  events = {fk.DamageCaused},
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    return target and H.compareKingdomWith(player, target) and player:hasSkill(self) and
      data.to:isAlive() and H.isSmallKingdomPlayer(data.to) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.damage = 0
    local targets = {}
    local num = 999
    for _, p in ipairs(room.alive_players) do
      local n = p.hp
      if n <= num then
        if n < num then
          num = n
          targets = {}
        end
        if n < p.maxHp then
          table.insert(targets, p.id)
        end
      end
    end
    if #targets > 0 then
      local to_heal = room:askForChoosePlayers(player, targets, 1, 1, "#hearlawsuit-choose", self.name, true)
      if #to_heal > 0 then
        room:recover{
          who = room:getPlayerById(to_heal[1]),
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
    end
    return true
  end,
}
caorui:addSkill(cuzhan)
cuzhan:addRelatedSkill(fight_targetmod)
cuzhan:addRelatedSkill(cuzhan_delay)
caorui:addSkill(tingsong)
Fk:loadTranslationTable{
  ["du_heg__caorui"] = "曹叡",
  ["#du_heg__caorui"] = "幽梦魏祚明",
  ["illustrator:du_heg__caorui"] = "Thinking",
  ["designer:du_heg__caorui"] = "陌小奈",
  ["hurryfight"] = "促战",
  [":hurryfight"] = "其他角色的出牌阶段开始时，你可以交给其一张牌，令其此阶段可多使用一张【杀】，且其立状：此阶段结束时，其于此阶段造成过伤害。<br>\
  <font color='red'>立状：若立状的角色于对应的时机未完成立状的任务，其必须执行一个随机军令。</font>",
  ["hearlawsuit"] = "听讼",
  [":hearlawsuit"] = "每回合限一次，与你势力相同的角色对小势力角色造成伤害时，你可以防止此伤害，然后你可令一名体力值最小的角色回复1点体力。",
  ["@@hurryfight-turn"] = "促战",
  ["@@fight-turn"] = "可多使用一张【杀】",
  ["#hurryfight_delay"] = "促战",
  ["#hurryfight-give"] = "促战：你可交给其一张牌",
  ["#hearlawsuit-ask"] = "听讼：你可选择一名角色，防止此伤害并令一名体力值最小的角色回复1点体力",
  ["#hearlawsuit-choose"] = "听讼：你可令一名体力值最小的角色回复1点体力",
  ["$hurryfight1"] = "今贼兵入寇中原，卿安然坐视乎？",
  ["$hurryfight2"] = "大魏的未来，托付给爱卿了！",
  ["$hearlawsuit1"] = "百姓若得人间之福，朕何辞地狱之苦。",
  ["$hearlawsuit2"] = "弘法明理,不负众民之望。",
  ["~du_heg__caorui"] = "悔不该耽于逸乐，至有今日。",
}












return extension